package model

import (
	"gorm.io/gorm"
	"group_-no.2/utils/errmsg"
	"time"
)

type Comment struct {
	User    User    `gorm:"foreignkey:UserID"`
	Article Article `gorm:"foreignkey:ArticleID"`
	gorm.Model
	Status    int8   `gorm:"type:tinyint;default:2" json:"status"`
	Content   string `gorm:"type:text;not null" json:"content"`
	UserID    uint   `gorm:"not null" json:"user_id"`
	ArticleID uint   `gorm:"not null" json:"article_id"`
}

type CommentResult struct {
	ID         uint      `json:"comment_id"`
	Status     int8      `json:"status"`
	Content    string    `json:"content"`
	UserID     uint      `json:"user_id"`
	UserName   string    `json:"user_name"`
	ArticleID  uint      `json:"article_id"`
	Title      string    `json:"title"`
	CreateTime time.Time `json:"create_time"`
}

func AddComment(data *Comment) int {
	err := db.Create(&data).Error
	if err != nil {
		return errmsg.ERROR
	}
	return errmsg.SUCCESS
}

func GetComment(id uint) (Comment, int) {
	var data Comment
	err := db.Where("id = ?", id).First(&data).Error
	if err != nil {
		return Comment{}, errmsg.ERROR
	}
	return data, errmsg.SUCCESS
}

func GetCommentList(pageSize int, pageNum int) ([]CommentResult, int64, int) {
	var commentList []CommentResult
	var total int64

	db.Find(&commentList).Count(&total)
	err := db.Model(&Comment{}).
		Limit(pageSize).
		Offset((pageNum - 1) * pageSize).
		Order("created_at desc").
		Select("comments.id, comments.user_id, comments.article_id, comments.status, " +
			"comments.content, comments.create_time, users.username, articles.title").
		Joins("left join users on comments.user_id = users.id").
		Joins("left join articles on comments.article_id = articles.id").
		Scan(&commentList).
		Error
	if err != nil {
		return nil, 0, errmsg.ERROR
	}

	return commentList, total, errmsg.SUCCESS
}

func GetCommentCount(id uint) int64 {
	var total int64
	db.Find(&Comment{}).Where("article_id = ?", id).Where("status = ?", 1).Count(&total)
	return total
}

func GetCommentListFromArticle(id uint, pageSize int, pageNum int) ([]CommentResult, int64, int) {
	var commentList []CommentResult
	var total int64

	total = GetCommentCount(id)
	err := db.Model(&Comment{}).
		Limit(pageSize).
		Offset((pageNum-1)*pageSize).
		Order("created_at desc").
		Select("comments.id, comments.user_id, comments.article_id, comments.status, "+
			"comments.content, comments.create_time, "+"users.username, articles.title").
		Joins("left join users on comments.user_id = users._id").
		Joins("left join articles on comments.article_id = articles.id").
		Where("article_id = ?", id).
		Where("status = ?", 1).
		Scan(commentList).
		Error

	if err != nil {
		return nil, 0, errmsg.ERROR
	}

	return commentList, total, errmsg.SUCCESS
}

func DeleteComment(id uint) int {
	var comment Comment
	err := db.Where("id = ?", id).Delete(&comment).Error
	if err != nil {
		return errmsg.ERROR
	}
	return errmsg.SUCCESS
}
